<template>
  <div class="edu-page-warp">
    <div class="coursemap">
      <a @click="previewCourse" style="color:#C0C4CC">课程分类管理</a>
      <span style="color:#C0C4CC">/</span>
      <span style="color:#909399">编辑课程分类</span>
    </div>
    <div style="margin-top:5px;margin-bottom: 20px;">
      <h2>
        {{this.title.name}} - {{this.title.yearStart}}~{{this.title.yearEnd ? this.title.yearEnd : '永久'}}
      </h2>
    </div>
    <div>
      <el-card shadow="never" body-style="padding: 24px;">
        <div class="edu-page-title">非公共选修课</div>
        <el-container>
          <el-aside width="30%" style="min-height:300px;">
            <el-row style="padding:15px 15px 15px 0;">
              <el-col :span="18">
                <el-input v-model="filterText" placeholder="快捷查询">
                  <i slot="suffix" class="el-icon-search" style="margin-top:10px;cursor:pointer"></i>
                </el-input>
              </el-col>
              <el-col :span="4" class="float-right" style="margin-right:15px;">
                <el-button plain size="mini" @click="addCourseCategory()">添加</el-button>
              </el-col>
            </el-row>
            <el-row>
              <el-tree class="filter-tree tree" :data="treeData" :props="defaultProps" default-expand-all
                :filter-node-method="filterNode" :highlight-current="true" @node-click="nodeClick" ref="tree"></el-tree>
            </el-row>
          </el-aside>
          <!-- 右边内容 -->
          <el-container>
            <el-main>
              <el-row>
                <el-form ref="detailForm" :model="detailForm" label-position="right" label-width="140px">
                  <template>
                    <el-row>
                      <div class="float-left">
                        <div class="edu-page-title">课程性质详情</div>
                      </div>
                    </el-row>
                    <el-row :gutter="20">
                      <el-col :span="12">
                        <el-form-item label="性质名称（中文）：">
                          <el-input v-model="detailForm.label" type="text" placeholder="请输入中文名称" style="width:100%"
                            maxlength="50" />
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row :gutter="20">
                      <el-col :span="12">
                        <el-form-item label="性质名称（英文）：">
                          <el-input v-model="detailForm.labelEn" placeholder="请输入英文名称" type="text" style="width:100%"
                            maxlength="50" />
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row :gutter="20" v-if="detailForm.parentID != 0">
                      <el-col :span="12">
                        <el-form-item label="归属课程性质 ：">
                          <el-select style="width: 100%;" v-model="detailForm.courseType" :placeholder="'请选择课程性质'"
                            clearable>
                            <el-option v-for="item in options.courseType" :key="item.id" :label="item.label"
                              :value="item.id"></el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </template>
                </el-form>
              </el-row>
              <!-- 添加类别-->
              <el-dialog :title="dialogTitle" :visible.sync="showCourseDialog" width="40%" @close="resetFormValidate()"
                :close-on-click-modal="false" :close-on-press-escape="false">
                <el-form ref="classifyForm" :model="classifyForm" :rules="courseRules" label-width="150px"
                  label-position="right" size="mini" class="bg-white">
                  <el-row :gutter="20">
                    <el-col :span="20" :offset="2">
                      <el-form-item label="类别名称（中文）：" prop="name">
                        <el-input v-model="classifyForm.name" type="text" placeholder="请输入中文名称" style="width:80%"
                          maxlength="50" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="20">
                    <el-col :span="20" :offset="2">
                      <el-form-item label="类别名称（英文）：" prop="nameEN">
                        <el-input v-model="classifyForm.nameEN" placeholder="请输入英文名称" type="text" style="width:80%"
                          maxlength="50" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="20">
                    <el-col :span="20" :offset="2">
                      <el-form-item label="归属课程类别 : ">
                        <el-select style="width: 80%;" v-model="classifyForm.courseType" :placeholder="'请选择课程类别'"
                          clearable>
                          <el-option v-for="item in options.courseType" :key="item.id" :label="item.label"
                            :value="item.id"></el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
                <el-row>
                  <el-col :span="24">
                    <div class="float-right">
                      <el-button @click="cancelAddCourseLab">{{ $t('common.btn.cancel') }}</el-button>
                      <el-button type="primary" @click="addCourseLabs">{{ $t('common.btn.confirm') }}</el-button>
                    </div>
                  </el-col>
                </el-row>
              </el-dialog>
            </el-main>
            <el-footer>
              <div class="float-right">
                <el-button size="mini" @click="deleteCourseLabs">删除</el-button>
                <el-button type="primary" size="mini" :disabled="!isEdit" @click="saveAll">保存</el-button>
              </div>
            </el-footer>
          </el-container>
        </el-container>
      </el-card>
    </div>
  </div>
</template>
<script>
  import {getClassifyNature, addMinorLable, editMinorLable, delMinorLable} from "common/src/api/minor/minorCourseManager"
  export default {
    data() {
      return {
        showCourseDialog: false,
        filterText: "",
        labType: 2, //1为公共选修课，2为非公共选修课
        isEdit: false,
        treeData: [],
        defaultProps: {
          children: "children",
          label: "label"
        },
        detailForm: {},
        options: {
          courseType: []
        },
        classifyForm: {
          nameCN: "",
          nameEN: "",
          courseType: "",
        },
        classifyOptions: {
          courseType: []
        },
        courseRules: {
          name: [{
              required: true,
              message: "请输入类别名称(中文)",
              trigger: "change"
            },
            {
              min: 1,
              max: 32,
              message: "长度在 1 到 32 个字符",
              trigger: "change"
            }
          ],
          nameEN: [{
            required: true,
            message: "请输入类别名称(英文)",
            trigger: "change"
          }]
        },
        title: {
          id: "",
          name: "",
          trainingLevel: "",
          yearStart: "",
          yearEnd: ""
        },
        newId: this.$route.query.id,
        isEditCourseLab: false,
      };
    },
    watch: {
      filterText(val) {
        this.$refs.tree.filter(val);
      },
      newId(newVal, oldVal) {
        if (newVal.length > 100) {
          this.clear();
          this.init();
        }
      },
      detailForm: {
        handler(newName, oldName) {
          if (oldName) {
            this.isEdit = true;
            this.isEditCourseLab = true;
          }
          if (newName.id !== oldName.id) {
            this.isEdit = false;
          }
        },
        deep: true
      }
    },
    created() {
      let bclOptionalCourse = JSON.parse(sessionStorage.getItem("minorOptionalCourse"));
      if (bclOptionalCourse) {
        this.title.id = bclOptionalCourse.id;
        this.title.name = bclOptionalCourse.classifyName;
        this.title.yearStart = bclOptionalCourse.minorGradeOri;
        this.title.yearEnd = bclOptionalCourse.minorGradeDest;
      }
      this.clear();
      this.init();
    },
    methods: {
      init() {
        this.labType = 2;
        this.getTreeData();
      },
      clear() {
        this.treeData = [];
        this.detailForm = []
      },
      previewCourse() {
        this.$router.push({
            path: '/minorCourseCategoryManage'
        })
      },
      getTreeData() {
        getClassifyNature(this.newId).then(res => {
          if (res.code == 200) {
            let data = res.data.map(item => {
              return {
                id: item.id,
                label: item.label,
                labelEn: item.labelEn,
                parentID: item.parentId ? item.parentId : "0",
              };
            });
            this.setTree(data);
          }
        });
      },
      setTree(data) {
        let parent = data.filter(item => {
          return item.parentID == 0;
        });
        let child = data.filter(item => {
          return item.parentID > 0;
        });
        if (child.length > 0) {
          parent.forEach(par => {
            par.children = [];
            child.forEach(chi => {
              if (par.id == chi.parentID) {
                chi.courseType = chi.parentID;
                par.children.push(chi);
              }
            });
          });
        }
        this.treeData = parent;
        this.options.courseType = parent;
        if (parent.length > 0) {
          this.detailForm = parent[0];
        }
      },
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      // 点击查看详情
      nodeClick(data, node, tree) {
        this.detailForm = data;
      },
      // 取消对话框课程分类
      cancelAddCourseLab() {
        this.classifyForm.courseType = "";
        this.showCourseDialog = false;
        this.resetFormValidate();
      },
      resetFormValidate() {
        // 清除表单校验
        this.$refs.classifyForm.resetFields();
      },
      // 添加课程类别
      addCourseCategory() {
        this.dialogTitle = "添加分类";
        this.showCourseDialog = true;
      },
      addCourseLabs() {
        //添加课程类别
        this.$refs.classifyForm.validate(valid => {
          if (!valid) {
            return;
          }
          let parms = {
            refId: this.newId,
            label: this.classifyForm.name,
            labelEn: this.classifyForm.nameEN,
            parentId: 0
          };
          if (this.classifyForm.courseType) {
            parms.parentId = this.classifyForm.courseType;
          }
          addMinorLable(parms)
            .then(res => {
              if (res.code == 200) {
                this.$message({
                  type: "success",
                  message: "添加成功"
                });
                this.classifyForm.courseType = "";
                this.showCourseDialog = false;
                this.getTreeData();
              }
            })
            .catch(error => {
              this.$message({
                type: "error",
                message: "添加失败"
              });
            });
        });
      },
      //删除课程类别
      deleteCourseLabs() {
        if (!this.detailForm.id) {
          this.$message({
            type: "warning",
            message: "请先选择要删除的课程"
          });
          return
        }
        let parms = {
          ids: [this.detailForm.id]
        };
        this.$confirm(
            "您确定要删除吗？",
            "提示", {
              confirmButtonText: this.$t("common.btn.confirm"),
              cancelButtonText: this.$t("common.btn.cancel"),
              type: "warning"
            }
          )
          .then(() => {
            delMinorLable(parms)
              .then(res => {
                if (res.code == 200) {
                  this.$message({
                    type: "success",
                    message: "删除成功"
                  });
                  this.clear();
                  this.getTreeData();
                }
              })
          });
      },
      // 保存
      saveAll() {
        if (this.isEditCourseLab) {
          this.isEditCourseLab = false;
          if (!this.detailForm.id) {
            this.$message({
              type: "warning",
              message: "请先选择需要修改的课程"
            });
            return
          }
          let parms = {
            id: this.detailForm.id,
            refId: this.newId,
            label: this.detailForm.label,
            labelEn: this.detailForm.labelEn,
            parentId: 0
          };
          if (this.detailForm.courseType) {
            parms.parentId = this.detailForm.courseType
          }
          editMinorLable(parms)
            .then(res => {
              console.log(77777)
              if (res.code == 200) {
                this.$message({
                  type: "success",
                  message: "保存成功"
                });
                this.getTreeData();
              }
            })
            .catch(error => {
              this.$message({
                type: "error",
                message: "保存失败"
              });
              this.getTreeData();
            });

        }
      }
    }
  };

</script>
<style scoped lang="scss">
  .coursemap {
    font-size: 12px;
    margin-bottom: 15px;
  }

  .el-tabs--border-card {
    background: #fff;
    border: none;
    -webkit-box-shadow: none;
    box-shadow: none;
  }

  .el-aside {
    padding: 0 20px;
    color: #333;
    border-right: 1px solid #cccc;
  }

  .el-main {
    padding: 20px;
    color: #333;
  }

  .el-footer {
    border-top: 1px solid #cccc;
    color: #333;
    line-height: 60px;
    text-align: right;
  }

  .addCourseBtn {
    margin-bottom: 15px;
  }

  .bluebg {
    display: inline-block;
    margin: 2px;
    padding: 4px 10px;
    color: blue;
    line-height: 1;
    vertical-align: middle;
  }

  .el-tag {
    margin-right: 10px;
    margin-bottom: 5px;
  }

</style>
